﻿//  --------------------------------
//  Copyright (c) Microsoft Corporation. All rights reserved.
//  This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//  http://www.codeplex.com/oxite/license
//  ---------------------------------
using System;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using ECube.Web.CMS;
using ECube.Web.CMS.Models;
using ECube.Web.CMS.Services;
using ECube.Web.CMS.Extensions;
namespace ECube.Web.CMS.ModelBinders
{
    public class PageModelBinder : IModelBinder
    {
        private readonly IPageService pageService;
        private readonly IUnityContainer container;

        public PageModelBinder(IPageService pageService, IUnityContainer container)
        {
            this.pageService = pageService;
            this.container = container;
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext.RouteData.Values.ContainsKey("id"))
            {
                Guid pid = controllerContext.RouteData.Values["id"].ToGuid();
                if (!pid.Equals(Guid.Empty))
                {
                    return pageService.GetPage(pid);
                }
            }
            else if (controllerContext.RouteData.Values.ContainsKey("pagePath"))
            {
                MvcSiteMapNodeModelBinder nodebinder = container.Resolve<MvcSiteMapNodeModelBinder>();
                if (nodebinder != null)
                {
                    MvcSiteMapNode node = nodebinder.BindModel(controllerContext, bindingContext) as MvcSiteMapNode;

                    if (node != null)
                    {
                        Page page = null;
                        Guid pageId = node.PageId.ToGuid();
                        if (!pageId.Equals(Guid.Empty))
                        {
                            page = pageService.GetPage(pageId);
                        }
                        if (page == null)
                        {
                            page = new Page(pageId) { SiteMapNodeKey = node.Key };
                        }
                        else
                        {
                            page.SiteMapNodeKey = node.Key;
                        }
                        return page;
                    }
                }
                return new Page(Guid.Empty);               
            }
            return null;            
        }
    }
}
